package com.magicborrow.adapter;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.beans.ApplyEntity;
import com.magicborrow.enums.PriceModeEnum;
import com.magicborrow.huanxin.ChatActivity;
import com.magicborrow.huanxin.Constant;
import com.magicborrow.utils.ImageLoadUtil;
import com.magicborrow.utils.StringUtil;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.view.ContactDialog;
import com.magicborrow.views.MsgDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ghost on 16/3/28.
 */
public class ApplyReceiverAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    private static final int TYPE_FOOT = 0;
    private static final int TYPE_NORMAL = 1;
    private ArrayList<ApplyEntity.ContentData> mData;
    private Context mContext;
    private LayoutInflater mLayoutInflater;

    public ApplyReceiverAdapter(Context pContext){
        this.mContext = pContext;
        mLayoutInflater = LayoutInflater.from(mContext);
    }

    public void setData(ArrayList<ApplyEntity.ContentData> pData){
        this.mData = pData;
    }

    public ArrayList<ApplyEntity.ContentData> getData(){
        return this.mData;
    }

    @Override
    public int getItemViewType(int position) {
        if(position+1 == getItemCount()){
            return TYPE_FOOT;
        }else{
            return TYPE_NORMAL;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(viewType == TYPE_FOOT){
            View view = mLayoutInflater.inflate(R.layout.load_more_footer,null);
            view.setTag("foot");
            return new FootViewHolder(view);
        }else if(viewType == TYPE_NORMAL){
            View view = mLayoutInflater.inflate(R.layout.apply_receive_item,null);
            return new ApplySendItemViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if(holder instanceof ApplySendItemViewHolder){
            final ApplySendItemViewHolder hold = (ApplySendItemViewHolder)holder;
            final ApplyEntity.ContentData bean = mData.get(position);
            // Log.e("ssss", Constants.ADDRESS+bean.getUser().getAvatar80());
            ImageLoadUtil.loadImage(hold.imv_head, Constants.ADDRESS+bean.getUser().getAvatar80().split("\\?")[0],R.mipmap.head_default);
            String url = "";
            if(bean.getWare().getImages() != null && bean.getWare().getImages().size() > 0){
                url = Constants.ADDRESS+bean.getWare().getImages().get(0).getPreview();
            }
            ImageLoadUtil.loadImage(hold.good_pic,url,R.mipmap.img_default);
            hold.good_name.setText(bean.getWare().getName());
            hold.tv_name.setText(bean.getUser().getNickname());
            hold.tv_address.setText("地址: "+bean.getWare().getAddress());
            hold.borrowTime.setText("借用时间: "+bean.getCreated());
            hold.borrowShichang.setText("借用时长: "+bean.getNumber()+ PriceModeEnum.getModeStr(bean.getWarePriceMode()));
            //hold.rbPingfen.setRating(bean.getUser().getLendScaleAVG());
            //hold.commentCountMsg.setText("" + StringUtil.double2String(bean.getUser().getLendScaleAVG()) + "（" + bean.getCommentCount() + "人评价）");

            float lendScaleAVG = bean.getUser().getLendScaleAVG();//借出者的信用评分
            hold.commentCountMsg.setText(lendScaleAVG+"分 ("+bean.getCommented()+"人评价)");
            hold.rb_pingfen.setRating(lendScaleAVG);
            hold.shouldPay.setText("应付金额: "+(bean.getNumber()*bean.getWarePrice()+bean.getWareDeposit()));
            operateStatus(bean.getStatus(),hold.statusMsg,hold.leftStatus,hold.rightStatus,hold.statusLayout);
            hold.leftStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int status = bean.getStatus();
                    String lm = hold.leftStatus.getText().toString();
                    if ("联系TA".equals(lm)) {
                        ContactDialog contactDialog = new ContactDialog(mContext
                                ,bean.getUser().getNickname()
                                ,bean.getUser().getId()
                                ,bean.getUser().getMobile()
                         , bean.getUser().getAvatar80());
                        contactDialog.show();
                      /*  mContext.startActivity(new Intent(mContext, ChatActivity.class).putExtra("chatType", 1)
                                .putExtra("userId", bean.getUser().getId() + "")
                                .putExtra("username", bean.getUser().getNickname()).putExtra("avatarPath",
                                        bean.getUser().getAvatar80()));*/
                    } else if (status == 0 && "同意".equals(lm)) {
                        sendRequest(bean, 1, position, "您已同意对方请求");
                    } else if (status == 1 && "提醒付款".equals(lm)) {
                        mContext.startActivity(new Intent(mContext, ChatActivity.class).putExtra("chatType", 1)
                                .putExtra("userId", bean.getUser().getId() + "")
                                .putExtra("username", bean.getUser().getNickname()).putExtra("avatarPath",
                                        bean.getUser().getAvatar80()));
                    } else if ((status == 3 || status == 5 || status == 6 || status == 7) && "已借出".equals(lm)) {
                        sendRequest(bean, 8, position, "请求已发送成功,");
                    } else if (status == 4 && "同意取消".equals(lm)) {
                        sendRequest(bean, 99, position, "您已同意取消");
                    }
                    }
            });
            hold.rightStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int status = bean.getStatus();
                    String rm = hold.rightStatus.getText().toString();
                    if(status == 0 && "拒绝".equals(rm)){
                        sendRequest(bean,2,position,"您已经拒绝对方申请!");
                    }else if(status == 1 && "取消借出".equals(rm)){

                        sendRequest(bean,99,position,"您已经取消该物品的借出!");

                    }else if(status == 3 && "取消借出".equals(rm)){
                        sendRequest(bean,9,position,"对方已付款,请等待对方同意您的取消请求!");
                    }else if(status == 4 && "拒绝取消".equals(rm)){
                        sendRequest(bean,7,position,"您已经拒绝取消,请尽快寄出物品!");
                    }
                }
            });
        }
    }

    private ProgressDialog progressDialog = null;
    private void sendRequest(final ApplyEntity.ContentData bean, final int cStatus, final int position, final String msg){
        progressDialog = new ProgressDialog(mContext);
        progressDialog.show();
        Map<String,String> params = new HashMap<>();
        params.put("id",bean.getId()+"");
        params.put("status",cStatus+"");
        params.put("acc_token", UserTools.getUser(mContext).getAcc_token());
        VolleyTool.get(Constants.FLOW_CONTROL, params, new VolleyTool.HTTPListener() {
            @Override
            public <T> void onResponse(T t, int requestCode) {
                try {
                    if(progressDialog != null){progressDialog.dismiss();}
                    JSONObject json = new JSONObject(t.toString());
                    int code = json.getInt("code");
                    if(code == 0){
                        new MsgDialog(mContext,msg,null).show();
                        mData.get(position).setStatus(cStatus);
                        if(cStatus == 8){
                            ApplyReceiverAdapter.this.notifyItemRemoved(position);
                        }else{
                            ApplyReceiverAdapter.this.notifyItemChanged(position);
                        }
                    }
                } catch (JSONException e) {
                    // e.printStackTrace();
                }
            }
            @Override
            public void onErrorResponse(VolleyError error, int requestCode) {
                if(progressDialog != null){progressDialog.dismiss();}
                Toast.makeText(mContext,"服务器暂时无法链接",Toast.LENGTH_SHORT).show();
            }
        },0,null);
    }

    private void operateStatus(int status,TextView statusMsg,TextView leftStatus,TextView rightStatus,RelativeLayout statusLayout){
        String sStatusMsg = "";
        String sLeftStatus = "";
        String sRightStatus = "";
        switch (status){
            case 0:
                sStatusMsg = "对方申请租借";
                sLeftStatus = "同意"; // 1
                sRightStatus = "拒绝";	// 2
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 1:
                sStatusMsg = "对方未付款";
                sLeftStatus = "提醒付款";
                sRightStatus = "取消借出"; // 99
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 2:
                sStatusMsg = "您已拒绝该申请";
                sLeftStatus = " "; 	// 无操作
                sRightStatus = " ";// 无操作
                statusLayout.setVisibility(View.GONE);
                break;
            case 3:
                sStatusMsg = "对方已付款";
                sLeftStatus = "已借出";	// 8
                sRightStatus = "取消借出";	// 5 // 弹窗确认（是否），请等待借用者回应<br>当借用这同意取消时即可取消
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 4:
                sStatusMsg = "对方申请取消借用";
                sLeftStatus = "同意取消"; // 99
                sRightStatus = "拒绝取消";  // 7 , 您已拒绝取消，请尽快将物品借出
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 5:
                sStatusMsg = "对方已付款 - 等待取消确认";
                sLeftStatus = "已借出"; // 8
                sRightStatus = " "; // 灰色
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 6:
                sStatusMsg = "对方拒绝取消";
                sLeftStatus = "已借出";	// 8
                sRightStatus = " ";// 不可点击
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 7:
                sStatusMsg = "物主拒绝取消";
                sLeftStatus = "已借出"; // 8
                sRightStatus = " ";// 不可点击
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 8:
                // case 不到 暂时先放着
                sStatusMsg = "申请借用成功";
                sLeftStatus = "联系TA";
                sRightStatus = "取消借用";
                statusLayout.setVisibility(View.GONE);
                break;
            case 9:
                sStatusMsg = "对方确认收到";
                sLeftStatus = "联系TA";
                sRightStatus = " ";
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 99:
                sStatusMsg = "已取消";
                sLeftStatus = "联系TA";
                sRightStatus = " ";
                statusLayout.setVisibility(View.VISIBLE);
                break;
        }
        statusMsg.setText(sStatusMsg);
        leftStatus.setText(sLeftStatus);
        rightStatus.setText(sRightStatus);
    }

    @Override
    public int getItemCount() {
        return mData.size()+1;
    }



    public class ApplySendItemViewHolder extends RecyclerView.ViewHolder {
        private ImageView imv_head;
        private TextView tv_name;
        private TextView statusMsg;
        private RatingBar rb_pingfen;
        private TextView commentCountMsg;
        private ImageView good_pic;
        private TextView good_name;
        private TextView borrowTime;
        private TextView borrowShichang;
        private TextView tv_address;
        private TextView shouldPay;
        private TextView leftStatus;
        private TextView rightStatus;
        private RelativeLayout statusLayout;

        public ApplySendItemViewHolder(View view) {
            super(view);
            statusLayout = (RelativeLayout)view.findViewById(R.id.statusLayout);
            imv_head = (ImageView)view.findViewById(R.id.imv_head);
            tv_name = (TextView)view.findViewById(R.id.tv_name);
            statusMsg = (TextView)view.findViewById(R.id.statusMsg);
            rb_pingfen = (RatingBar)view.findViewById(R.id.rb_pingfen);
            commentCountMsg = (TextView)view.findViewById(R.id.commentCountMsg);
            good_pic = (ImageView)view.findViewById(R.id.good_pic);
            good_name = (TextView)view.findViewById(R.id.good_name);
            borrowTime = (TextView)view.findViewById(R.id.borrowTime);
            borrowShichang = (TextView)view.findViewById(R.id.borrowShichang);
            tv_address = (TextView)view.findViewById(R.id.tv_address);
            shouldPay = (TextView)view.findViewById(R.id.shouldPay);
            leftStatus = (TextView)view.findViewById(R.id.leftStatus);
            rightStatus = (TextView)view.findViewById(R.id.rightStatus);
        }
    }

    public class FootViewHolder extends RecyclerView.ViewHolder{

        public FootViewHolder(View itemView) {
            super(itemView);
        }

    }

}
